package com.lh.music.service;

import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.widget.RemoteViews;

import com.lh.music.IMusic.IMusic;
import com.lh.music.PlayApplication;
import com.lh.music.R;
import com.lh.music.constant.Constants;
import com.lh.music.dao.SongDao;
import com.lh.music.entity.Song;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

public class PlayService extends Service {
    private PlayApplication app;
    //private List<Song> songList=new ArrayList<>();
    //private int songPosition;
    private MediaPlayer player;
    private Binder playBinder;
    public PlayService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        app= (PlayApplication) getApplication();
        System.out.println("服务被创建");
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        playBinder=new PlayBinder();
        app.music= (IMusic) playBinder;
        return  playBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
       /* if (player!=null){
            player.stop();
            player.release();
            player=null;
        }*/
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("服务被销毁");
    }

    class PlayBinder extends Binder implements IMusic{

        @Override
        public void initMusic(List<Song> list, int position) {
            //更新播放位置
            app.currentPosition=position;
        }

        @Override
        public void startPlay() {
            if (app.currentSongList.size()==0){
                return;
            }else{
                app.currentSong=app.currentSongList.get(app.currentPosition);
                //更新表中的正在播放歌曲
                try {
                    SongDao dao=new SongDao(getApplicationContext());
                    dao.updateNowPlaySong(app.currentSong);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                //更改状态
                app.currentType=Constants.LOCAL;
                app.songState= Constants.PLAYING;
                player=new MediaPlayer();
                player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    player.setDataSource(app.currentSongList.get(app.currentPosition).getData());
                    player.prepare();//先准备好
                    player.start();//再开始播放
                    updateNoti();
                    //获取歌曲的总长度
                    app.currentDuration=player.getDuration();
                    player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            nextPlay();
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }

        @Override
        public void stopPlay() {
            if (player!=null){
                player.stop();
                player.release();
                player=null;
            }
        }

        @Override
        public void pausePlay() {
            if (player!=null&&player.isPlaying()){
                player.pause();
                app.songState=Constants.PAUSED;
            }
            updateNoti();
        }

        @Override
        public void continuePlay() {
            if (player!=null&&!player.isPlaying()){
                player.start();
                app.songState=Constants.PLAYING;
            }
            updateNoti();
        }

        @Override
        public void nextPlay() {
            //如果当前播放位置为歌曲列表的最后一个，将位置置为0
            if (app.currentPosition==app.currentSongList.size()-1){
                app.currentPosition=0;
            }else{
                app.currentPosition++;
            }
            stopPlay();
            startPlay();
            updateNoti();
        }

        @Override
        public void prevPlay() {
            //如果当前播放位置为歌曲列表的第一个，将位置置为size-1
            if (app.currentPosition==0){
                app.currentPosition=app.currentSongList.size()-1;
            }else{
                app.currentPosition--;
            }
            stopPlay();
            startPlay();
            updateNoti();
        }

        @Override
        public int getSongState() {
            return app.songState;
        }

        @Override
        public int getSongProgress() {
            if (player!=null){
                return player.getCurrentPosition();
            }
            return 0;
        }

        @Override
        public void seekToProgress() {
            if (player!=null){
                player.seekTo(app.currentProgress);
            }
        }


    }
    //更新播放的通知栏中的UI
    private void updateNoti(){
        RemoteViews views=app.notification.contentView;
        if (app.currentSong!=null){
            views.setTextViewText(R.id.song_name,app.currentSong.getTitle());
            views.setTextViewText(R.id.artist_name,app.currentSong.getArtist());
        }
        Intent controlIntent=null;
        PendingIntent controllPendin=null;
        //根据不同的状态   为控制播放按钮添加不同的单击监听
        switch (app.songState){
            case  Constants.PAUSED:
                views.setImageViewResource(R.id.controll_play,R.mipmap.play);
                //添加控制播放对应的监听
                controlIntent=new Intent(Constants.CONTINUE_ACTION);
                controllPendin=PendingIntent.getBroadcast(this,0,controlIntent,PendingIntent.FLAG_UPDATE_CURRENT);
                views.setOnClickPendingIntent(R.id.controll_play,controllPendin);
                break;
            case  Constants.PLAYING:
                views.setImageViewResource(R.id.controll_play,R.mipmap.pause);
                controlIntent = new Intent(Constants.PAUSE_ACTION);
                controllPendin = PendingIntent.getBroadcast(this, 0, controlIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                views.setOnClickPendingIntent(R.id.controll_play,controllPendin);
                break;
        }
        app.notificationManager.notify(Constants.NOTI_ID,app.notification);
    }

}
